package com.songcha.sakura.mvvm.downloading

import android.os.*
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.LinearLayoutManager
import com.songcha.library_base.mvvm.base.BaseMvvmFragment
import com.songcha.library_base.mvvm.base.BaseRepository
import com.songcha.library_common.util.ToastUtil
import com.songcha.sakura.R
import com.songcha.sakura.databinding.FragmentLocalVideoBinding
import com.songcha.sakura.download.*
import com.songcha.sakura.ui.adapter.DownloadTaskAdapter
import com.songcha.sakura.ui.adapter.diff.DownloadTaskDiffCallback
import com.songcha.sakura.download.base.DownloadTask
import com.songcha.sakura.download.base.TaskState
import com.songcha.sakura.event.*
import com.songcha.sakura.ui.base.BaseComicMvvmFragment
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


class DownloadingFragment: BaseComicMvvmFragment<DownloadingViewModel, FragmentLocalVideoBinding>() {

    companion object{
        val TAG:String= DownloadingFragment::class.java.simpleName
    }
    //private var _binding: FragmentLocalVideoBinding? = null

    //private var mTaskList:MutableList<DownloadTask> = mutableListOf()
    //private var mOldTaskList:MutableList<DownloadTask> = mutableListOf()

    private var mAdapter:DownloadTaskAdapter?=null


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

    }


    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return super.onCreateView(inflater, container, savedInstanceState)
    }

    override fun getLayoutId(): Int {
        return R.layout.fragment_local_video
    }


    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)

        EventBus.getDefault().register(this)

        databinding.rcvDownload.apply {
            layoutManager= LinearLayoutManager(this@DownloadingFragment.requireContext())

            val adt=DownloadTaskAdapter(context, R.layout.item_download_task,viewModel.taskList.value!!)
            mAdapter=adt
            adapter=adt

            adt.setOnItemChildClickListener{a,v,p->
                when(v.id){
                    R.id.ib_control->{
                        val task=viewModel.taskList.value!![p]
                        controlTask(task)
                    }
                }

            }
            adt.setOnItemClickListener{a,v,p->


            }
        }

        viewModel.taskList.observe(viewLifecycleOwner){taskList->
            diffUpdate(taskList)
        }

    }



    override fun onResume() {
        super.onResume()

        //LogUtil.log("aaa","DownloadServiceController.isConnect",DownloadServiceController.isConnect())
        if(!DownloadServiceController.isConnect()){
            viewModel.pauseAllTask()
        }

    }



    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    fun onLocalTaskList(event:LocalTaskListEvent){
        EventBus.getDefault().removeStickyEvent(event)
        viewModel.updateTaskList(event.taskList)
        //diffUpdate()
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    fun onTaskList(event: TaskListEvent){
        EventBus.getDefault().removeStickyEvent(event)
        viewModel.updateTaskList(event.taskList)
        //diffUpdate()
    }

    fun diffUpdate(list:MutableList<DownloadTask>){
        mAdapter?.let {
            val diffResult=DiffUtil.calculateDiff(DownloadTaskDiffCallback(viewModel.oldTaskList,list))
            diffResult.dispatchUpdatesTo(it)
            viewModel.updateOldTaskList()
        }

    }


    fun controlTask(task:DownloadTask){
        if(!DownloadServiceController.isConnect()){
            ToastUtil.show("下载服务重启中")
            //val fileName=task.option.fileName.substring(12,task.option.fileName.length)
            //LogUtil.log("aaa",task.url,task.option.fileName)
            DownloadServiceController.bindService(object:IServiceConnectionListener{
                override fun onConnected() {

                }

                override fun onConnectInitialize() {
                    DownloadServiceController.createTask(task.url,"",task.option.fileName)
                }
            })
            return
        }


        if(task.state== TaskState.DOWNLOADING){
            ToastUtil.show("暂停任务")
            //DownloadManager.pauseTask(task)
            DownloadServiceController.pauseTask(task)
        }else{
            ToastUtil.show("开始任务")
            //listener,option,downloadDelegate
            //DownloadManager.resumeTask(task)
            DownloadServiceController.resumeTask(task)
        }

    }


    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }


    /*fun notifiyItemChanged(t:DownloadTask){
        val idx=isInTaskList(t)
        if(idx>-1){
            viewModel.taskList[idx]=t
            diffUpdate()
        }
    }*/

    @Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
    fun onDownloadServiceDisConnect(event:DownloadServiceDisconnectedEvent){
        /*for(task in mTaskList){
            task.state==TaskState.PAUSE
        }*/
        viewModel.pauseAllTask()
        //diffUpdate()
        //mAdapter?.notifyDataSetChanged()
    }

    @Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
    fun onDwloadTaskChange(event: DownloadTaskEvent) {
        //LogUtil.log("aaa",event.type)
        when(event.type){
            DownloadTaskEventType.INITIALIZE->{
                event.task?.let {
                   //addItem(it)
                    viewModel.addItem(it)
                }

            }

            DownloadTaskEventType.START->{
                event.task?.let {
                    //notifiyItemChanged(it)
                    viewModel.notifiyItemChanged(it)
                }
            }

            DownloadTaskEventType.UPDATE->{
                event.task?.let {
                    //notifiyItemChanged(it)
                    viewModel.notifiyItemChanged(it)
                }

            }

            DownloadTaskEventType.COMPLETED->{
                event.task?.let {
                    viewModel.removeItem(it)
                }
            }

            DownloadTaskEventType.PAUSE->{
                event.task?.let {
                    viewModel.notifiyItemChanged(it)
                }
            }

            DownloadTaskEventType.ERROR->{
                event.task?.let {
                    //LogUtil.log("aaa","  DownloadTaskEventType.ERROR",it.state)
                    //notifiyItemChanged(it)
                    //removeItem(it)
                    viewModel.removeItem(it)
                }
            }

            DownloadTaskEventType.CANCEL->{
                event.task?.let {
                    viewModel.removeItem(it)
                }
            }

            else -> {}
        }
    }

    /*fun addItem(task:DownloadTask){
        val idx=isInTaskList(task)
        if(idx>-1){
            mTaskList[idx]=task
        }else{
            mTaskList.add(0,task)
        }
        diffUpdate()
    }

    fun removeItem(task:DownloadTask){
        val idx=isInTaskList(task)
        if(idx>-1){
            mTaskList.removeAt(idx)
            diffUpdate()
        }
    }*/

   /* fun getAdapter():DownloadTaskAdapter{
        return  _binding?.rcvDownload?.adapter as DownloadTaskAdapter
    }*/


  /*  private fun isInTaskList(id:Long):Int{
        for(i in 0 until mTaskList.size){
            if(mTaskList[i].downloadEntity.id==id){
                return i
            }
        }

        return -1
    }*/







}